package com.xuxiang;

/**
 * @author xuxiang 2019/8/2 16:48
 */
public class HashMap<K, V> {

    static class Node<K, V> {
        K key;
        V value;
        Node next;
    }

    private Node<K, V>[] nodes;
    private int size = 0;

    public HashMap(int size) {
        this.size = size;
        this.nodes = new Node[size];
    }

    private int pos(K k) {
        return k.hashCode() % size;
    }

    public void put(K k, V v) {
        int pos = pos(k);
        if (nodes[pos] == null) {
            nodes[pos] = new Node();
            nodes[pos].key = k;
            nodes[pos].value = v;
        } else {
            Node<K, V> node = getNode(k);
            if (node != null) {
                node.value = v;
            } else {
                node = new Node();
                node.key = k;
                node.value = v;
                node.next = nodes[pos];
                nodes[pos] = node;
            }
        }
    }

    public V get(K k) {
        int pos = pos(k);
        Node<K, V> node = getNode(k);
        return node == null ? null : node.value;
    }

    public Node<K, V> getNode(K k) {
        int pos = pos(k);
        if (nodes[pos] == null) {
            return null;
        } else {
            Node<K, V> node = nodes[pos];
            while (node != null) {
                if (node.key.equals(k)) {
                    return node;
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String a = "";
        String b = "";
        System.out.println(String.join(",", a, b));
    }

}
